package com.cg.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName ParamFilter
 * @Description 属性过滤器
 * @Author CG
 * @Date 2023/11/24 16:00
 **/

public class ParamFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //过滤规则，请求中的参数携带着
        ServerHttpRequest request = exchange.getRequest();
        String sourceType = request.getHeaders().getFirst("source-type");
        if(sourceType == null || sourceType.equals("")){
            logger.info("source-type不存在");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        String timestamp = request.getHeaders().getFirst("timestamp");
        if(timestamp == null || timestamp.equals("")){
            logger.info("timestamp不存在");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        String userString = request.getPath().toString();
        if(userString.indexOf("/user/login")<0){
            //除了登录之外的url
            String token = request.getHeaders().getFirst("token");
            if(token == null || token.equals("")){
                logger.info("token不存在");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
